import {wechatUserInfo,getToken} from '@/utils';
import { debounce } from '@/utils/helper';
import { Button, Image, View } from '@tarojs/components';
import Taro from '@tarojs/taro';
import React, { useEffect, useRef } from 'react';
import './index.scss';

const getUserProfile = async (codeRef) => {
  let profile;

  if (typeof wx.getUserProfile !== 'undefined') {
    profile = await wx.getUserProfile({
      desc: '为提供优质服务',
    });
  } else {
    profile = await wx.getUserInfo({
      withCredentials: true,
      lang: 'zh_CN',
    });
  }

  const { encryptedData, iv, rawData, signature } = profile;
  let loginType = 'WECHAT'
  if(process.env.TARO_ENV === 'tt') loginType = 'DOUYIN'
  if(process.env.TARO_ENV === 'alipay') loginType = 'ALIPAY'
  const { code, content, message } = await Taro.$post('/mb/logins',{
    username: Taro.$mpAppid,
    loginType,
    password: codeRef.current,
    wechatInfoReq: {
      encryptedData,
      iv,
      rawData,
      signature,
    },
  })

  if (code !== '1') {
    throw new Error(message);
  }

  const {
    token: { accessToken },
  } = content;

  wechatUserInfo.set({
    code: codeRef.current,
    accessToken,
    userInfo: profile.userInfo,
    profile,
  });

  if (content?.openId) {
    // dispatch({
    //   type: 'login/setOpenId',
    //   payload: content.openId,
    // });
    Taro.setStorageSync('openID',content.openId);
  }
};

const WechatAuth = ({ next }) => {
  const codeRef = useRef();
  const appConfig = Taro.getStorageSync('appConfig') || {}

  // 进入页面先获取 code
  useEffect(() => {
    Taro.login({
      success: (res) => {
        codeRef.current = res.code;
      },
    });
  }, []);

  const generallyLogin = debounce(() => {
    // getUserProfile(dispatch, codeRef)
    //   .then(() => {
    //     next();
    //   })
    //   .catch((e) => {
    //     console.warn(e);

    //     if (/auth deny/.test(e?.errMsg ?? '')) {
    //       Taro.showModal({
    //         title: '提示',
    //         content:
    //           '您已拒绝，将无法登录使用；如需登录使用，请再次点击按钮，并在微信授权窗口点击允许',
    //       });
    //     }
    //   });
  }, 2000);

  // 已经登录, 直接返回上一个页面
  useEffect(() => {
    if (getToken()) {
      Taro.navigateBack();
    }
  }, []);

  return (
    <View className="WechatAuth">
      <View className="title">欢迎使用 {appConfig?.name}</View>
      <View className="info">授权微信头像、昵称</View>
      <View className="logo">
        <Image src={appConfig?.iconUrl || require('@/images/gray.jpg')} className="img" />
      </View>
      <View className="label">为提供优质服务，{appConfig?.name}需要获取你的以下信息：</View>
      <View className="notice">· 你的公开信息（头像、昵称等）</View>

      <Button className="reset-btn btn customePageBackgroundStyle" onClick={generallyLogin}>
        <View className="txt">手机号快捷登录</View>
      </Button>
    </View>
  );
};
export default WechatAuth;